package role_api

import (
	"benkendSystem/api/menu_api"
	"benkendSystem/database"
	"benkendSystem/models"
	"github.com/gin-gonic/gin"
	"net/http"
)

// GetRoleMenus 根据角色ID获取所有菜单数据列表
//func GetRoleMenus(roleId int64, isAdmin bool) (*gorm.DB, error) {
//	tx := new(gorm.DB)
//	if isAdmin {
//		tx = database.DB.Model(new(models.Menu)).Select("id,parent_id, component_name,name,icon,order,path,level").Order("order ASC")
//	} else {
//		roleBasic := new(models.Role)
//		err := database.DB.Model(new(models.Role)).Select("id").Where("id = ?", roleId).First(roleBasic).Error
//		if err != nil {
//			return nil, err
//		}
//		tx = database.DB.Model(new(models.RoleMenu)).Select("mb.id, mb.parent_id, mb.component_name, mb.name, mb.icon, mb.order, mb.path, mb.level").
//			Joins("LEFT JOIN menu mb on mn.id = role_menu.menu_id").
//			Where("role_menu.role_id = ?", roleBasic.ID).Order("mb.order ASC")
//	}
//	return tx, nil
//}

// GetMenuFromRoleId 根据角色ID获取菜单权限
func GetMenuFromRoleId(c *gin.Context) {
	id := c.Request.URL.Query().Get("role_id")
	data := make([]*menu_api.MenuReply, 0)
	allMenus := make([]*menu_api.AllMenu, 0)
	var isAdmin bool
	err := database.DB.Model(new(models.Role)).Select("is_admin").Where("id = ?", id).Find(&isAdmin).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "系统错误",
		})
		return
	}
	if isAdmin {
		err = database.DB.Model(new(models.Menu)).Select("id,parent_id, component_name,name,icon,`order`,path,level").Find(&allMenus).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 500,
				"msg":  "系统错误",
			})
			return
		}
		data = menu_api.AllMenuToMenuReply(allMenus)
		c.JSON(http.StatusOK, gin.H{
			"code":   200,
			"msg":    "操作成功",
			"result": data,
		})
	} else {
		err = database.DB.Model(new(models.Menu)).Select("menu.id,menu.parent_id, menu.component_name,menu.name,menu.icon,menu.`order`,menu.path,menu.level").Joins("left join role_menu rm on menu.id=rm.menu_id").Where("rm.role_id = ? and menu.deleted_flag != 1", id).Find(&allMenus).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 500,
				"msg":  "系统错误",
			})
			return
		}
		data = menu_api.AllMenuToMenuReply(allMenus)
		c.JSON(http.StatusOK, gin.H{
			"code":   200,
			"msg":    "操作成功",
			"result": data,
		})
	}

}
